var express = require('express')
    , router = express.Router()
    , mathHelper = require('../helper/math')
    , R = require('../helper/rands')
    , C = require('../helper/core')
    , L = require('../helper/lists')

// router.get('/start', (req, res) => {
//     res.json({
//         results: '3 5 7 19 98 66 23 13 99 38 75'
//     })
// })

function get_rand_nums_between(min, max, num) {
    const nums_between = C.nums_between(min, max)
    const rand_distinct_nums = R.get_no_repeat_list(nums_between, num).filter(C.is_not_null)
    for (let i = rand_distinct_nums.length; i < num; i++) {
        rand_distinct_nums.push(nums_between.find(L.is_not_in_fn(rand_distinct_nums)))
    }
    return rand_distinct_nums
}

function pretreat_input(req) {
    min = parseInt(req.body.start)
    max = parseInt(req.body.end)
    num = parseInt(req.body.num)
    return [min, max, num]
}

function is_input_valid(min, max, num) {
    return min <= max && num <= (max - min)
}

/**
 * 不需要验证用户身份
 * TODO: 将记录保存到数据库
 */
function start_handler(req, res) {
    //console.log(req.body)
    var result = {
        ok: true,
        datas: [],
        msg: '',
    }

    try {
        const [min, max, num] = pretreat_input(req)
        if (is_input_valid(min, max, num)) {
            result.datas = get_rand_nums_between(min, max, num)
            res.json(result)
        } else {
            result.ok = false
            result.msg = '输入值无效!'
            res.json(result)
        }
    } catch (e) {
        result.ok = false
        result.msg = '输入不合法!'
        res.json(result)
    }
}

router.post('/start', start_handler)

module.exports = router